package com.lhl.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author hanLin.liu
 * @create 2024-10-29 15:33
 */
public class NIOClient {
    public static void main(String[] args) {

        try(SocketChannel socketChannel = SocketChannel.open();
            Scanner scanner = new Scanner(System.in)){
            // 连接到服务器
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 8888));
            System.out.println("发送消息(退出请输入quit)：");
            while (scanner.hasNext()){
                String msg = scanner.nextLine();
                if ("quit".equals(msg)){
                    break;
                }
                socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
                System.out.printf("发送成功!消息内容:【%s】\n",msg);
                handleRead(socketChannel);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

    }
    private static void handleRead(SocketChannel channel) throws IOException {

        // 创建缓冲区对象【默认是写模式】
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        int byteSize = channel.read(byteBuffer);
        if(byteSize > 0){
            // 切换读模式
            byteBuffer.flip();
            String msg = new String(byteBuffer.array(), 0, byteSize);
            System.out.printf("收到了来自【%s】响应：【", channel.getRemoteAddress());
            System.out.println(msg + "】");
        }
    }
}
